//
//  SEDoctorAuthViewController.swift
//  SmartEyeForDoctor
//
//  Created by qdsg on 2021/5/6.
//

import UIKit
import Photos

enum SEDoctorAuthViewControllerType {
    case mine
    case register
}

class SEDoctorAuthViewController: SEBaseViewController {

    var viewModel = SEDoctorAuthViewModel()

    var submitSucessHandler: (() -> Void)?

    convenience init(type: SEDoctorAuthViewControllerType, userInfoModel: SEUserInfoModel) {
        self.init()
        viewModel.userInfoModel = userInfoModel
        viewModel.type = type
    }


    @IBOutlet weak var reasonViewHeight: NSLayoutConstraint! {
        didSet {
            if viewModel.userInfoModel.isAuthenticate == .reject {
                let rejectReasonHeight = 45 + viewModel.rejectionReason.height(width: UIScreen.screenWidth - 30, font: UIFont.regular(14))
                reasonViewHeight.constant = rejectReasonHeight
            } else {
                reasonViewHeight.constant = 0
            }

        }
    }


    @IBOutlet weak var reasonLabel: UILabel! {
        didSet {
            reasonLabel.text = viewModel.rejectionReason
        }
    }

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = tableFooterView
            tableView.rowHeight = UITableView.automaticDimension
            tableView.register(SEDoctorAuthCell.nibForCell(), forCellReuseIdentifier: SEDoctorAuthCell.reuseIdentifier())
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "医师认证"
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()
        view.backgroundColor = UIColor.white

        viewModel.updateData = { status in
            switch status {
            case .success:
                SEHUD.show(message: "提交成功")
                if self.viewModel.type == .mine {
                    self.submitSucessHandler?()
                    self.navigationController?.popViewController(animated: true)
                } else {
                    UIApplication.shared.keyWindow?.rootViewController = SETabBarController()
                }
            case .auth(let msg):
                self.presentLoginViewController(selector: nil) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.uploadHandler = { status in
            switch status {
            case .success:
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: nil) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

    }

    private lazy var tableFooterView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 50 + 48 + 10 + 20 + 20))
        let btnView = SEConfirmBtnView(frame: CGRect(x: 15, y: 50, width: UIScreen.screenWidth - 30, height: 48))
        btnView.delegate = self
        btnView.title = "提交审核"
        view.addSubview(btnView)
        if viewModel.type == .register {
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: 0, y: 50 + 48 + 10, width: 30, height: 20)
            btn.centerX = view.centerX
            btn.setTitle("跳过", for: .normal)
            btn.setTitleColor(Asset.textLight.color, for: .normal)
            btn.titleLabel?.font = UIFont.regular(14)
            btn.addTarget(self, action: #selector(nextBtnAction), for: .touchUpInside)
            view.addSubview(btn)
        }
        return view
    }()

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEDoctorAuthViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEDoctorAuthCell.reuseIdentifier(), for: indexPath) as! SEDoctorAuthCell
        cell.updateData(viewModel.dataSource[indexPath.row])
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        viewModel.imageType = SEDoctorAuthImageType(rawValue: indexPath.row) ?? .idCard
        SEAlert.showImagePickerSheet(in: self) { _ in
            self.checkCameraPermission()
        } photoHandler: { _ in
            self.openPhotoLibrary()
        }
    }
}

extension SEDoctorAuthViewController: SEConfirmBtnViewDelegate {
    func confirmBtnViewAction(view: SEConfirmBtnView) {
        submitDoctorAuth()
    }

    @objc func nextBtnAction() {
        UIApplication.shared.keyWindow?.rootViewController = SETabBarController()
    }
}

// MARK: - APIRequest

extension SEDoctorAuthViewController {
    func submitDoctorAuth() {
        viewModel.submitDoctorAuth()
    }
}

// MARK: - UIImagePickerControllerDelegate

extension SEDoctorAuthViewController {
    private func checkCameraPermission() {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        switch authStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { (granted) in
                if !granted {
                    dispatch_async_safely_main_queue {
                        SEAlert.show(in: self.navigationController,
                                     title: "无法访问您的相机",
                                     message: "请到设置 -> 隐私 -> 相机 ，打开访问权限",
                                     confirmTitle: "去设置") { _ in
                            SEOpenSettingURL()
                        }
                    }
                }
            }
        case .restricted, .denied:
            SEAlert.show(in: self.navigationController,
                         title: "无法访问您的相机",
                         message: "请到设置 -> 隐私 -> 相机 ，打开访问权限",
                         confirmTitle: "去设置") { _ in
                SEOpenSettingURL()
            }
        case .authorized:
            openCamera()
        default:
            break
        }
    }

    private func openCamera() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }

    private func openPhotoLibrary() {
        UIScrollView.appearance().contentInsetAdjustmentBehavior = .automatic
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.modalPresentationStyle = .custom
        present(imagePicker, animated: true, completion: nil)
    }
}

extension SEDoctorAuthViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            viewModel.uploadImg(image: image)
        }
        dismiss(animated: true) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
    }
}

